<template>
  <div class="page-common-layout">
    <div class="page-common-left" style="width:25%;padding: 0">
      <div class="header">
        <span class="title">
          字典分类
        </span>
        <span>
          <a-icon type="edit" @click="openOperation()" v-action:dicSet_add />
        </span>
      </div>
      <div class="padding-xs">
        <a-input-search
          placeholder="字典分类名称"
          style="width: 100%"
          @search="onSearch"
        />
      </div>
      <div class="body">
        <a-tree
          v-if="showTree"
          ref="masterList"
          blockNode
          show-icon
          default-expand-all
          :tree-data="treeData"
          :replaceFields="replaceFields"
          @select="selectTree"
          :selected-keys="treeSelectedKeys"
        >
          <template #title="{ dicSetCode: treeKey, dicSetName }">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ dicSetName }}</span>
              <template #overlay>
                <a-menu
                  :data-clipboard-text="treeKey"
                  id="copyBtn"
                  @click="
                    ({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)
                  "
                >
                  <a-menu-item key="1">复制字典集代码</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-tree>
      </div>
    </div>
    <div class="page-common-content">
      <tool-bar
        ref="toolBar"
        @search="fetch"
        @reset="reset"
        :showDivisionBar="true"
        :showToolBtn="false"
      >
        <template slot="toolForm">
          <a-form-item label="名称">
            <a-input
              v-model="subQueryParam.dicItemName"
              placeholder="名称"
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="编码">
            <a-input
              v-model="subQueryParam.dicItemCode"
              placeholder="编码"
              style="width: 200px"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <a-button
        class="cu-btn-primary margin-bottom-xs"
        icon="plus"
        @click="handleAdd"
        v-action:dicSet_add
      >
        新建
      </a-button>
      <a-button class="margin-bottom-xs" icon="reload" @click="refreshCache">
        刷新缓存
      </a-button>

      <div :style="{ height: tableHeight }">
        <a-table
          ref="subList"
          size="small"
          :columns="columns"
          :data-source="dataSource"
          rowKey="uuid"
          showPagination="auto"
          :pagination="pagination"
          :scroll="scrollXY"
          :rowClassName="rowClassName"
          :customRow="rowClick"
          @change="handleTableChange"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="renderDicItemStatus" slot-scope="text, record, index">
            <a-switch
              size="small"
              :checked="text == 'true' ? true : false"
              @change="(e) => stateChange(e, record)"
            />
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleEdit(record)" v-action:dicSet_edit>编辑</a>
              <span class="action-margin"></span>
              <a
                @click="handleSub(record)"
                class="action-delete"
                v-action:dicSet_delete
              >
                删除
              </a>
            </template>
          </span>
        </a-table>
      </div>
    </div>
    <operation
      :visible="operationVisible"
      @reloadTree="reloadTree"
      @cancel="operationVisible = false"
      @ok="operationOk"
    />
    <sub-form
      ref="subModal"
      :visible="subVisible"
      :loading="subConfirmLoading"
      :model="subMdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </div>
</template>
<script>
import subForm from "./subEdit.vue";
import operation from "./operation.vue";

export default {
  name: "TableList",
  components: {
    subForm,
    operation,
  },
  data() {
    return {
      columns: [
        {
          title: "序号",
          align: "center",
          width: 50,
          scopedSlots: {
            customRender: "serial",
          },
        },
        {
          title: "名称",
          dataIndex: "dicItemName",
          width: 200,
        },
        {
          title: "编码",
          dataIndex: "dicItemCode",
          width: 200,
        },
        {
          title: "状态",
          dataIndex: "dicItemStatus",
          align: "center",
          width: 80,
          scopedSlots: { customRender: "renderDicItemStatus" },
        },
        {
          title: "排序",
          dataIndex: "dicItemSort",
          align: "center",
          width: 80,
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          width: 120,
          scopedSlots: { customRender: "action" },
        },
      ],
      // create model
      subVisible: false,
      masterConfirmLoading: false,
      subConfirmLoading: false,
      masterMdl: null,
      subMdl: null,
      // 查询参数
      subQueryParam: {},
      parameter: {
        father: {
          levelId: 1,
          pid: 1,
        },
        children: {},
      },
      replaceFields: {
        children: "children",
        title: "dicSetName",
        key: "uuid",
      },
      showTree: false,
      operationVisible: false,
      rawTreeData: [],
      treeData: [],
      pagination: {
        pageNo: 1,
        pageSize: 20,
        showSizeChanger: true,
        showQuickJumper: true,
        hideOnSinglePage: false,
        pageSizeOptions: ["20", "50", "100", "500"],
        onShowSizeChange: (current, pageSize) =>
          this.onShowSizeChange(current, pageSize),
      },
      pageClientHeight: 0,
      dataSource: [],
      selectedRowKeys: [],
      rowKeys: "",
      selectedKeys: "",
      toolbarHeight: 0,
      //
      treeSelectedKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      };
    },
    scrollXY() {
      let height = "";
      height = this.pageClientHeight - (50 + this.toolbarHeight);
      const tdHeight = this.dataSource?.length * 40 ?? 0;
      return this.dataSource?.length >= 20 || height < tdHeight
        ? { y: height, x: "100%" }
        : { x: "100%" };
    },
    tableHeight() {
      let height = "";
      if (!this.toolbarHeight) {
        height = `calc(100% - 152px)`;
      } else {
        height = `calc(100% - ${this.toolbarHeight}px)`;
      }
      return height;
    },
  },
  mounted() {
    this.getTreeSysDicSet();
    this.resizeHandler();
    this.initResizeEvent();
  },
  beforeDestroy() {
    this.destroyResizeEvent();
  },
  methods: {
    resizeHandler() {
      this.toolbarHeight = this.$refs.toolBar.$el.clientHeight + 89;
      // 获取页面内容的高度
      this.pageClientHeight = document.getElementsByClassName(
        "page-common-content"
      )[0]?.clientHeight;
    },
    fetch() {
      this.subQueryParam.pageSize = this.pagination.pageSize;
      this.subQueryParam.pageNo = this.pagination.pageNo;
      this.$post("/system/dicItem/getPageSet", this.subQueryParam).then(
        (res) => {
          const pager = {
            ...this.pagination,
          };
          pager.total = res.totalCount;
          this.dataSource = res.rows;
          this.pagination = pager;
        }
      );
    },
    onShowSizeChange(current, pageSize) {
      const pager = { ...this.pagination };
      pager.pageSize = pageSize;
      pager.pageNo = current;
      this.pagination = pager;
      this.fetch();
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.pageNo = pagination.current;
      this.pagination = pager;
      this.fetch();
    },
    reset() {
      this.subQueryParam = {};
      if (this.selectedKeys) {
        this.subQueryParam.puuid = this.selectedKeys;
      }
      this.fetch();
    },
    openOperation() {
      this.operationVisible = true;
    },
    getTreeSysDicSet() {
      this.$post(`/system/dicSet/getTreeSysDicSet?systemdic=y`)
        .then((res) => {
          if (res.statusCode === 200) {
            this.treeData = res.data;
            this.rawTreeData = res.data;
            this.treeSelectedKeys = [this.treeData?.[0]?.uuid];
            this.subQueryParam.puuid = this.treeData?.[0]?.uuid;
            this.fetch();
            this.showTree = true;
          }
        })
        .catch((_) => {});
    },
    //搜索数据
    onSearch(value) {
      this.showTree = false;
      if (value) {
        this.treeData = this.treeFilter(
          value,
          JSON.parse(JSON.stringify(this.rawTreeData))
        );
      } else {
        this.treeData = this.rawTreeData;
      }
      this.$nextTick(() => {
        this.showTree = true;
      });
    },
    selectTree(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.treeSelectedKeys = [uuid];
      this.subQueryParam.puuid = uuid;
      this.selectedKeys = uuid;
      this.fetch();
      //   this.treeSelectedKeys = selectedKeys;
      //   delete this.subQueryParam.puuid;
      //   this.selectedKeys = "";
      //   if (info.selected) {
      //     this.subQueryParam.puuid = selectedKeys[0];
      //     this.selectedKeys = selectedKeys[0];
      //   }
      //   this.fetch();
    },
    treeFilter(value, arr) {
      if (!arr) {
        return [];
      }
      let newarr = [];
      arr.forEach((item) => {
        if (item.dicSetName.indexOf(value) > -1) {
          let redata = this.treeFilter(value, item.children);
          let obj = {
            ...item,
            children: redata,
          };
          newarr.push(obj);
        } else {
          if (item.children && item.children.length > 0) {
            let redata = this.treeFilter(value, item.children);
            let obj = {
              ...item,
              children: redata,
            };
            if (redata && redata.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    },
    onContextMenuClick(treeKey, menuKey) {
      let clipboard = new this.clipboard("#copyBtn");
      clipboard.on("success", (e) => {
        this.$message.success("已复制到粘贴面板，字典集代码为：" + treeKey);
        clipboard.destroy();
      });
      clipboard.on("error", (e) => {
        this.$message.error("复制失败！");
        clipboard.destroy();
      });
    },
    handleAdd() {
      if (!this.subQueryParam.puuid) {
        this.$message.warn("请先选中左侧字典分类数据", 1.5);
        return true;
      }
      this.subMdl = {
        puuid: this.subQueryParam.puuid,
      };
      this.$refs.subModal.form.resetFields();
      this.subVisible = true;
      this.$refs.subModal.title = "新增";
      this.subMdl.dicItemStatus = true;
    },
    handleEdit(record) {
      this.subVisible = true;
      this.subMdl = JSON.parse(JSON.stringify(record));
      this.$refs.subModal.title = "编辑";
      this.subMdl.dicItemStatus = record.dicItemStatus == "true" ? true : false;
    },
    handleSub(record) {
      const that = this;
      that.$confirm({
        title: that.$ct("tips", "提示"),
        content: that.$ct(
          "deleteConfirmationPrompt",
          "确定删除该数据吗？删除之后不可恢复！"
        ),
        okText: that.$ct("confirm", "确定"),
        cancelText: that.$ct("cancel", "取消"),
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that
            .$post("/system/dicItem/delete", {
              uuid: record.uuid,
            })
            .then((res) => {
              if (res.statusCode === 200) {
                that.$message.success(res.message);
                that.fetch();
              } else {
                that.$message.info(res.message);
              }
            });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    },
    handleCancel() {
      this.subVisible = false;
    },
    handleOk() {
      const form = this.$refs.subModal.form;
      this.subConfirmLoading = true;
      let url = "";
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.uuid) {
            url = "/system/dicItem/update";
          } else {
            url = "/system/dicItem/save";
          }
          this.$post(url, values)
            .then((res) => {
              if (res.statusCode === 200) {
                this.subVisible = false;
                this.fetch(this.subQueryParam);
                this.$message.success(res.message || "操作成功", 1.5);
              } else {
                this.$message.error(res.message || "操作失败", 1.5);
              }
            })
            .finally(() => {
              this.subConfirmLoading = false;
            });
        } else {
          this.subConfirmLoading = false;
        }
      });
    },
    rowClick(record, index) {
      const that = this;
      return {
        on: {
          click: () => {
            that.rowKeys = record.uuid;
          },
        },
      };
    },
    rowClassName(row) {
      return row.uuid === this.rowKeys ? "bg-bray" : ""; // 每条数据的唯一识别值
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    stateChange(value, record) {
      event.stopPropagation();
      let param = {
        puuid: record.puuid,
        uuid: record.uuid,
        dicItemStatus: value,
        dicItemCode: record.dicItemCode,
      };
      this.$post("/system/dicItem/update", param).then((res) => {
        if (res.statusCode === 200) {
          this.$message.success(res.message, 1.5);
          this.fetch();
        } else {
          this.$message.warn(res.message, 1.5);
        }
      });
    },
    operationOk() {
      this.operationVisible = false;
    },
    reloadTree() {
      this.getTreeSysDicSet();
    },
    refreshCache() {
      this.$post("/system/dicItem/refresCache").then((res) => {
        if (res.statusCode === 200) {
          this.$message.success(res.message, 1.5);
        } else {
          this.$message.warn(res.message, 1.5);
        }
      });
    },
    initResizeEvent() {
      window.addEventListener("resize", this.resizeHandler, false);
    },
    //移除resize
    destroyResizeEvent() {
      window.removeEventListener("resize", this.resizeHandler);
    },
  },
};
</script>

<style lang="less" scoped="scoped">
.page-common-left {
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    color: #606266;
    padding: 10px;
    height: 50px;
    box-sizing: border-box;

    .title {
      font-size: 16px;
    }
  }

  .body {
    padding: 10px;
    overflow: auto;
    flex: 1;
  }
}
</style>
